﻿using System;
using System.Xml.Linq;
using Engine;
using Game;

namespace ApiToolkit
{
	public class SinglePropertyEditor : CanvasWidget
	{
		private void getValueLimit(out float start, out float end)
		{
			switch(Editor.TargetPropertyName)
			{
			    default:
			        start = float.MinValue;
	    		    end = float.MaxValue;
	    		    break;
			}
		}

		public SinglePropertyEditor(int content, string targetProperty, ContainerWidget parent)
		{
			this.Editor = new PropertyEditor_Common(content, targetProperty);
			
			XElement xelement = ContentManager.Get<XElement>("Widgets/SinglePropertyEditor");
			base.LoadContents(this, xelement);
			this.ValueSlider = Children.Find<SliderWidget>("ValueSlider");
			this.ValueTextBox = Children.Find<TextBoxWidget>("ValueTextBox");
			this.ApplyButton = Children.Find<ButtonWidget>("ApplyButton");
			this.value = (float)Editor.TargetPropertyValue;
			this.ValueTextBox.Text = value.ToString();
		}
		
		private static float Clamp(float value, float min, float max)
		{
			if(value > max) return max;
			if(value < min) return min;
			return value;
		}
		public override void Update()
		{
			if (ValueSlider.SlidingCompleted)
			{
				float offset = ValueSlider.Value;
				
				getValueLimit(out float start, out float end);
				if (offset + value < start || offset + value > end)
				{
					offset = Clamp(value + offset, start, end) - value;
				}
				value += offset;
				ValueSlider.Value = 0f;
				ValueTextBox.Text = value.ToString();
			}
			else if (ValueSlider.IsSliding)
			{
				float offset = ValueSlider.Value;
				if (offset != 0)
				{
					ValueTextBox.Text = (value + offset).ToString();
				}
			}
			else if (value.ToString() != ValueTextBox.Text)
			{
				try
				{
					value = float.Parse(ValueTextBox.Text);
				}
				catch
				{
					this.ValueTextBox.Text = value.ToString();
				}
			}
			if (this.ApplyButton.IsClicked)
			{
				this.Editor.TargetPropertyValue = this.value;
			}
		}
		#region MemberWidgets
		private ContainerWidget Parent;
		
		private SliderWidget ValueSlider;
		
		private TextBoxWidget ValueTextBox;
		
		private ButtonWidget ApplyButton;
		#endregion
		
		private PropertyEditor_Common Editor;
		
		private float value;
	}
}